<!-- eslint-disable vue/valid-v-slot -->
<!-- eslint-disable vue/no-lone-template -->
<template>
  <div class="main-container">
    <TableBody>
      <template #header>
        <TableHeader ref="tableHeaderRef" :show-filter="false">
          <template #search-content>
            <a-form ref="forms" :model="form">
              <a-row :gutter="24">
                <a-col :span="4">
                  <a-form-item field="name" hide-label>
                    <a-input
                      v-model.trim="form.name"
                      class="width100"
                      placeholder="请输入应用名称"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="btns" hide-label>
                    <a-space :size="15">
                      <a-button
                        type="primary"
                        v-permission="webAppList"
                        html-type="submit"
                        @click="doRefresh(1)"
                        ><template #icon> <icon-search /> </template>搜索</a-button
                      >
                      <a-button v-permission="webAppList" @click="resetSeach"
                        ><template #icon>
                          <icon-sync theme="outline" size="14" />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>重置</template></a-button
                      >
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </template>
        </TableHeader>
      </template>
      <template #table-config>
        <a-space :size="15">
          <a-button type="primary" v-permission="addWebApp" @click="openApp">添加</a-button>
        </a-space>
        <a-space :size="15">
          <TableConfig
            @update-border="onUpdateBorder"
            @update-striped="onUpdateStriped"
            @refresh="doRefresh"
          />
        </a-space>
      </template>
      <template #default>
        <a-table
          :bordered="{ wrapper: true, cell: tables.bordered }"
          :stripe="(tables.striped as boolean)"
          :loading="tables.tableLoading"
          :data="tableColumns.list1"
          :pagination="false"
          :column-resizable="true"
          :rowKey="rowKey"
          :columns="tableColumns.list"
          table-layout-fixed
          hide-expand-button-on-empty
          :default-expand-all-rows="true"
          :scroll="{ x: 1500 }"
          :scrollbar="{ type: 'track', outerClass: '', outerStyle: '' }"
        >
          <template #columns>
            <a-table-column
              v-for="item of tableColumns.list"
              :key="item.key"
              align="left"
              :title="(item.title as string)"
              :width="item.width"
              :data-index="(item.key as string)"
              :fixed="item.fixed"
              :ellipsis="true"
              :tooltip="true"
            >
              <template v-if="item.key === 'number'" #cell="{ record }">
                {{ record.paths.length }}个
              </template>
              <template v-if="item.key === 'butten'" #cell="{ record }">
                <a-space>
                  <a-button v-permission="updateWebApp" type="text" @click="detailFn(record)"
                    >编辑</a-button
                  >
                  <a-button
                    type="text"
                    v-permission="'/app/application/web/add/file'"
                    @click="upFn(record)"
                    >上传</a-button
                  >
                  <a-button
                    type="text"
                    :disabled="record.paths.length > 0 ? false : true"
                    @click="pathFn(record)"
                    >查看</a-button
                  >
                  <a-button type="text" v-permission="deleteWebApp" @click="appDelete(record.name)"
                    >删除</a-button
                  >
                  <a-button type="text" v-permission="clearWebApp" @click="appClear(record.name)"
                    >清空</a-button
                  >
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </TableBody>
    <!-- 添加 -->
    <a-modal
      v-model:visible="addVisible"
      width="650px"
      :mask-closable="false"
      @before-close="appClose"
      title-align="start"
      :title="title"
    >
      <a-form ref="formNameRef" :auto-label-width="true" :model="formName">
        <a-form-item
          label="应用名称"
          field="name"
          asterisk-position="end"
          :rules="[
            { required: true, message: '请输入模板名称' },
            { minLength: 1, maxLength: 20, message: '长度在 1 - 20个字符' },
          ]"
        >
          <a-input placeholder="请输入应用名称" v-model.trim="formName.name" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="appClose">取消</a-button>
          <a-button type="primary" @click="addApp">确定</a-button>
        </a-space>
      </template>
    </a-modal>
    <!-- 查看 -->
    <a-modal
      v-model:visible="detailVisible"
      width="650px"
      :mask-closable="false"
      title-align="start"
      title="查看"
    >
      <!-- <div style="margin-bottom: 10px" v-for="(item, index) in list" :key="index"
          >{{ item }}
          <a-button style="margin-left: 10px" type="text" @click="copy(item)">复制</a-button>
        </div> -->
      <div style="height: 500px; overflow-y: auto">
        <a-tree
          v-model:checked-keys="selectList"
          :data="list"
          :field-names="{ key: 'path', title: 'name' }"
        >
          <template #extra="nodeData">
            <div v-if="!nodeData.children" style="color: #349efa" @click="copy(nodeData)">
              复制
            </div>
          </template>
        </a-tree>
      </div>
      <!-- <a-tree
        :checkable="true"
        checked-strategy="child"
        :data="list"
        :default-expand-all="false"
        :field-names="{ key: 'children', title: 'path' }"
      > -->
      <!-- <template #extra="nodeData"> -->
      <!-- <div v-if="nodeData.show == true" style="color: #349efa"> 首页 </div>
            <div v-else-if="nodeData.show == false" @click="sys(nodeData)" style="color: #86909c">
              设置首页
            </div>
            <div v-else-if="nodeData.show == 2"> </div> -->
      <!-- </template> -->
      <!-- </a-tree> -->

      <template #footer>
        <a-space />
      </template>
    </a-modal>
    <!-- 上传 -->
    <a-modal
      v-model:visible="upVisible"
      width="650px"
      :mask-closable="false"
      title-align="start"
      title="上传"
      @before-close="upClose"
      ><a-form ref="upFormRef" :auto-label-width="true" :model="upForm">
        <a-form-item label="上传文件" asterisk-position="end">
          <a-upload
            action="/app/application/web/add/file"
            :file-list="listTXT"
            @success="onSuccess"
            @error="onError"
            :data="{
              name: upForm.name,
              decompression: upForm.decompression,
              clean: upForm.clean,
            }"
            :limit="1"
            @before-upload="beforeUpload"
            :auto-upload="false"
            ref="uploadRefs"
          >
            <template #upload-button>
              <a-button type="outline">上传文件</a-button>
            </template>
          </a-upload>
        </a-form-item>
        <a-form-item
          v-if="state == true"
          label="是否解压"
          field="decompression"
          asterisk-position="end"
        >
          <a-radio-group
            class="radio-bcg"
            v-model="upForm.decompression"
            @change="upForm.clean = true"
          >
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">解压</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">不解压</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="state == true && upForm.decompression == true"
          label="是否清空"
          field="clean"
          asterisk-position="end"
        >
          <a-radio-group class="radio-bcg" v-model="upForm.clean">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">清空</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">不清空</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>

      <template #footer>
        <a-space>
          <a-button @click="upClose">取消</a-button>
          <a-button type="primary" @click="addUp">确定</a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { webAppList, addWebApp, deleteWebApp, updateWebApp, clearWebApp } from '@/api/url'

  import { get } from '@/api/http'
  import { usePagination, useRowKey } from '@/hooks/table'
  import { onMounted, reactive, ref } from 'vue'

  import _ from 'lodash-es'
  import { Message, Modal } from '@arco-design/web-vue'

  const pagination = usePagination(doRefresh)

  const forms = ref()

  const addVisible = ref(false)

  const detailVisible = ref(false)

  const upVisible = ref(false)

  const formNameRef = ref()
  const name = ref('')

  const title = ref('添加应用')

  const formName: any = ref({
    name: '',
  })

  const selectList = ref([])

  const upForm: any = ref({
    name: '',
    decompression: true, // 是否解压true解压， false不解压
    file: '', // 文件
    clean: true,
  })

  const form = reactive({
    name: '', //应用名称
  })

  const tables = reactive({
    tableLoading: false,
    bordered: false,
    striped: false,
    expand: [1],
    isExpand: false,
  })

  const tableColumns: any = reactive({
    list: [
      {
        title: '应用名称',
        key: 'name',
        dataIndex: 'name',
        align: 'left',
        checked: true,
        width: 400,
      },
      {
        title: '文件数量',
        key: 'number',
        dataIndex: 'number',
        align: 'left',
        checked: true,
        width: 400,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        align: 'left',
        checked: true,
        width: 190,
      },
      {
        title: '操作',
        key: 'butten',
        dataIndex: 'butten',
        align: 'left',
        checked: true,
        fixed: 'right',
        width: 400,
      },
    ],
  })

  const rowKey = useRowKey('id')

  const resetSeach = () => {
    forms.value.resetFields()
    doRefresh(1)
  }

  function upFn(val: any) {
    upForm.value.name = val.name
    upVisible.value = true
  }

  const state = ref(false)

  function upClose() {
    listTXT.value = []
    state.value = false
    upVisible.value = false
  }

  const uploadRefs = ref()

  function addUp() {
    console.log('111')
    uploadRefs.value.submit()
  }

  function beforeUpload(file) {
    return new Promise((resolve, reject) => {
      const lists = [
        'zip',
        'rar',
        '7z',
        'tar',
        'gz',
        'tgz',
        'bz',
        'tbz',
        'bz2',
        'tbz2',
        'xz',
        'txz',
        'lzma',
        'tlzma',
        'z',
      ]

      lists.forEach((item) => {
        if (file.name.search(item) != -1) {
          return (state.value = true)
        } else {
          state.value = false
        }
      })

      resolve(true)
    })
  }

  const listTXT = ref()

  const onSuccess = (fileItem) => {
    upClose()
    doRefresh()
    Message.success('上传成功')
  }

  const onError = (fileItem: any) => {
    Message.error(fileItem.response.msg)
  }

  const list = ref([])

  function pathFn(val: any) {
    name.value = val.name
    list.value = val.paths

    detailVisible.value = true
  }

  function copy(val: any) {
    console.log(val)
    //val复制的值
    let url =
      window.location.protocol +
      '//' +
      window.location.host +
      '/web/webapp/' +
      name.value +
      val.path
    let input = document.createElement('input')
    input.value = url
    input.id = 'creatDoms'
    document.body.appendChild(input)
    input.select()
    document.execCommand('copy')
    document.body.removeChild(input)
    // ===========================
    Message.success('复制成功')
  }

  function openApp() {
    addVisible.value = true
    title.value = '添加应用'
  }

  function appClose() {
    formName.value.targetName = ''
    formNameRef.value.resetFields()
    addVisible.value = false
  }

  function addApp() {
    console.log(formName.value.name)
    formNameRef.value.validate((error: any) => {
      if (!error) {
        if (formName.value.targetName) {
          updateApps()
        } else {
          addApps()
        }
      }
    })
  }

  function detailFn(val: any) {
    const obj = JSON.parse(JSON.stringify(val))
    formName.value.name = ''
    formName.value.targetName = obj.name
    title.value = '编辑应用'
    addVisible.value = true
  }

  function updateApps() {
    get({
      url: updateWebApp,
      data: {
        name: formName.value.targetName,
        targetName: formName.value.name,
      },
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        appClose()
        doRefresh()
      }
    })
  }

  function addApps() {
    get({
      url: addWebApp,
      data: {
        name: formName.value.name,
      },
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        appClose()
        doRefresh()
      }
    })
  }
  deleteWebApp

  function appDelete(val: any) {
    Modal.warning({
      title: '操作确认',
      content: '确定要删除此应用？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '确定',
      onOk() {
        get({
          url: deleteWebApp,
          data: {
            name: val,
          },
        }).then((res) => {
          if (res.code == 0) {
            Message.success(res.msg)
            doRefresh()
          }
        })
      },
    })
  }

  function appClear(val: any) {
    Modal.warning({
      title: '操作确认',
      content: '确定要清空应用？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '确定',
      onOk() {
        get({
          url: clearWebApp,
          data: {
            name: val,
          },
        }).then((res) => {
          if (res.code == 0) {
            Message.success(res.msg)
            doRefresh()
          }
        })
      },
    })
  }

  //我的短信列表
  function doRefresh(value?: number) {
    tables.tableLoading = true
    if (value) {
      pagination.page = value
    }
    get({
      url: webAppList,
      data: {
        ...form,
        page: pagination.page,
        size: pagination.pageSize,
      },
    }).then((res) => {
      tables.tableLoading = false
      tableColumns.list1 = res.data
      pagination.setTotalSize((res.data as any).totalSize)
      return res.data
    })
  }

  function onUpdateBorder(isBordered: boolean) {
    tables.bordered = isBordered
  }

  function onUpdateStriped(isStriped: boolean) {
    tables.striped = isStriped
  }

  onMounted(async () => {
    await doRefresh()
  })
</script>

<style lang="less" scoped>
  ::-webkit-scrollbar {
    width: 3px;
    height: 0.75rem;
    background-color: #f5f5f5;
  }
  :deep(.arco-table-cell-expand-icon) {
    justify-content: center;
  }
  :deep(.arco-table-td-content button) {
    padding: 0px !important;
    margin-right: 8px;
    background: none !important;
  }
  :deep(.arco-tabs-nav-tab) {
    background-color: var(--color-bg-1);
    padding: 20px 0;
    border-radius: 10px;
  }

  :deep(.arco-tabs-content::before) {
    height: 0px !important;
  }

  :deep(.arco-tabs-tab) {
    margin: 0 20px;
    padding: 0;
    padding-bottom: 5px;
  }

  :deep(.arco-tabs-nav::before) {
    position: static !important;
    height: 0px !important;
  }

  :deep(.arco-tabs-content) {
    padding-top: 20px;
  }

  .box {
    overflow: hidden; //超出的文本隐藏
    text-overflow: ellipsis; //用省略号显示
    white-space: nowrap;
  }

  .tabs {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 40px;
    margin-bottom: 20px;

    .button {
      box-sizing: border-box;
      padding-bottom: 5px;
    }
  }

  .action {
    color: #009dff;
    border-bottom: 3px solid #009dff;
  }

  .butten {
    padding: 0px 4px;
  }
</style>
